﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FyndSharp.Utilities.Common;
using FyndSharp.Data;
using FyndSharp.Data.Orm;
using Fynd.Hermes.Web.Objects;
using System.Data.Common;
using System.Data;
using System.IO;

namespace Fynd.Hermes.Web.Pages
{
    public partial class ManagedFileDownload : RoleBasedPage
    {
        protected override IEnumerable<UserRole> AccreditedRoles
        {
            get
            {
                return new UserRole[] { UserRole.NormalUser, UserRole.Administrator };
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            LinkBack.NavigateUrl = Request.UrlReferrer == null ? "ManagedFileList.aspx" : Request.UrlReferrer.ToString();

            string managedFileId = TypeConvert.ToString(Request.QueryString["id"]);
            if (String.IsNullOrEmpty(managedFileId))
            {
                LabelMessage.Text = "找不到这样的文件，回去再找找？";
                return;
            }

            AdoSession db = AdoSessionManager.Current["hermes"];
            bool isDbOpen = false;
            ManagedFile theFile = null;
            try
            {
                isDbOpen = db.Open();

                string sql = OrmObjectFactory.CreateSelectSql(typeof(ManagedFile));
                sql += " WHERE managed_file_id = @id";
                using (DbCommand cmd = db.CreateCommand(sql))
                {
                    cmd.Parameters.Add(db.CreateParameter("@id", DbType.String, managedFileId));
                    DataTable dt = db.ExecuteDataTable(cmd);
                    if (dt.Rows.Count <= 0)
                    {
                        LabelMessage.Text = "找不到这样的文件，回去再找找？";
                        return;
                    }
                    theFile = OrmObjectFactory.CreateOrmObject<ManagedFile>(dt.Rows[0]);
                }

                string absPath = (Global.UploadRootPath.StartsWith("~/")
                    ? Server.MapPath(Global.UploadRootPath)
                    : Global.UploadRootPath)
                + theFile.RelativePath;
                if (File.Exists(absPath) == false)
                {
                    LabelMessage.Text = "找不到这样的文件，回去再找找？";
                    return;
                }

                UserInfomation theUser = Context.Items[Global.HttpContextKeyUser] as UserInfomation;
                DateTime now = DateTime.Now;
                OperationLog log = new OperationLog()
                {
                    CreatedBy = theUser.LoginName,
                    CreatedDate = now,
                    ModifiedBy = theUser.LoginName,
                    ModifiedDate = now,
                    Message = String.Format("{0}({1})于{2}下载了文件{3}，IP：{4}"
                        , theUser.TrueName
                        , theUser.EmployeeNumber
                        , now.ToString()
                        , theFile.RelativePath
                        , Request.UserHostAddress),
                    OperationDate = now,
                    ClientIP = Request.UserHostAddress,
                    UserLoginName = theUser.LoginName,
                    OperatorTrueName = theUser.TrueName
                };
                OrmObjectFactory ormFactory = new OrmObjectFactory(
                    delegate()
                    {
                        return Guid.NewGuid().ToString();
                    }
                    , db);
                using (DbCommand logCmd = ormFactory.CreateSaveDbCommand(log))
                {
                    db.ExecuteNonQuery(logCmd);
                }
                Response.AppendHeader("content-disposition", "attachment; filename=" + Path.GetFileName(absPath));
                Response.ContentType = "application/vnd.android.package-archive";
                Response.WriteFile(absPath);
                
            }
            finally
            {
                if (isDbOpen)
                {
                    db.Close();
                }
            }
            Response.End();


        }
    }
}